<template>
	<view class="codeBtn" @click="sendCode" :class="{ disable: disableCode }">
		{{ sendBtnText }}
	</view>
</template>

<script>
	export default {
		name: "sendMsg",
		data() {
			return {
				sendBtnText: "获取验证码",
				disableCode: false,
				timer: null,
			};
		},
		props: {
			phone: {
				type: [Number, String]
			},
			event:{
				type:String
			}
		},
		methods: {
			sendCode() {
				if(this.disableCode) return false
				if(!this.phone)
				{
					this.$toast('请输入手机号')
					return
				}
				const reg = /^1[3-9]\d{9}$/;
				if (!reg.test(this.phone)) {
					this.$toast('手机号格式错误')
					return
				  }
				this.disableCode = true;
				if (this.disableCode) {
					this.$post("/user/sms", {
						phone: this.phone,
						event:this.event,
					}).then((res) => {
						console.log(res)
						if (res.code == 200) {
							this.countDown();
						} else {
							this.$toast(res.msg);
							this.disableCode = false;
						}
					});
				}
			},
			countDown() {
				let counter = 60;
				// 将setInterval()方法赋值给前面定义的timer计时器对象，等用clearInterval()方法时方便清空这个计时器对象
				this.sendBtnText = `已发送(${counter}秒)`;
				this.timer = setInterval(() => {
					this.sendBtnText = `已发送(${counter - 1}秒)`;
					counter--;
					if (counter == 0) {
						// 当计时小于零时，取消该计时器
						clearInterval(this.timer);
						this.disableCode = false;
						this.sendBtnText = `重新发送`;
					}
				}, 1000);
			},
		}
	}
</script>

<style lang="scss">
	.codeBtn {
		color: #51C76C;
		font-size: 28rpx;
		position: absolute;
		right: 0%;
		top: 50%;
		transform: translateY(-50%);
	}

	.disable {
		opacity: 0.5;
	}
</style>